package com.lottery.material.controller.portal.article;

import com.alibaba.fastjson.JSON;
import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.pojo.article.ArticleChargePricingConfig;
import com.lottery.material.pojo.article.ArticleInfo;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.circle.CircleMemberInfo;
import com.lottery.material.pojo.conf.MenuLevelConfig;
import com.lottery.material.pojo.conf.VocabularyFilterConfig;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.pojo.portaluser.PortalUserInfo;
import com.lottery.material.resolver.CustomException;
import com.lottery.material.service.portal.article.ArticleChargePricingConfigService;
import com.lottery.material.service.portal.article.ArticleInfoService;
import com.lottery.material.service.portal.circle.CircleInfoService;
import com.lottery.material.service.portal.circle.CircleMemberInfoService;
import com.lottery.material.service.portal.menu.MenuLevelConfigService;
import com.lottery.material.service.portal.user.PortalUserInfoService;
import com.lottery.material.util.*;
import com.lottery.material.vo.portal.article.ArticleAuthVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:houjie
 * @Description: 发帖相关接口类
 * @Date:Create in 2019/4/8 14:01
 */
@Api(value = "发帖相关接口", tags = { "发帖相关接口" })
@Controller
@RequestMapping("/portal/article")
@Slf4j
public class ArticlePostController extends BaseController {

    @Autowired
    PortalUserInfoService portalUserInfoService;
    @Autowired
    CircleMemberInfoService circleMemberInfoService;
    @Autowired
    CircleInfoService circleInfoService;
    @Autowired
    ArticleInfoService articleInfoService;
    @Autowired
    MenuLevelConfigService menuLevelConfigService;
    @Autowired
    ArticleChargePricingConfigService articleChargePricingConfigService;

    /**
     * @Author: houjie
     * @Description: 验证用户的发帖权限
     * @Date: 2019/4/8 14:47
     */
    @ApiOperation(value="发帖验证", notes="用户发帖权限验证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "circleId", value = "圈子id", required = true, dataType = "String")
    })
    @RequestMapping("/checkArticleAuth")
    @ResponseBody
    public ResponseResult checkArticleAuth(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String userId = reqParamMap.get("userId");
        if (StringUtils.isBlank(userId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "userId");
        }
        String circleId = reqParamMap.get("circleId");
        if(StringUtils.isBlank(circleId)){
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "circleId");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if(null != responseResult){
            return responseResult;
        }

        PageData pd = new PageData();
        pd.put("userId",userId);
        pd.put("circleId",circleId);
        //根据用户userId及圈子circleId获取圈成员信息
        CircleMemberInfo circleMemberInfo = circleMemberInfoService.findByUserIdAndCircleId(pd);
        if(AssertUtil.isEmpty(circleMemberInfo)){
            return ResponseResult.buildResult(400,"您还未关注过该圈子，不能在该圈内发帖！");
        }
        //判断圈成员是否被禁言
        if(circleMemberInfo.getIsBan()==2){//被禁言
            return ResponseResult.buildResult(400,"您已被圈主禁言，无权在该圈内发帖！");
        }
        //根据圈子id查询圈子信息
        CircleInfo circleInfo = circleInfoService.findById(Integer.valueOf(circleId));
        pd.put("nowDate",CalendarUtil.getNowDate("yyyy-MM-dd")+" 00:00:00");
        List<ArticleInfo> articleInfoList = articleInfoService.findTheDayByUserIdAndCircleId(pd);
        //判断用户发帖时间是否已经满足时间间隔
        if(AssertUtil.isNotEmpty(articleInfoList)){
            ArticleInfo articleInfo=articleInfoList.get(0);
            if(CalendarUtil.interval(articleInfo.getCreateTime().getTime())<circleInfo.getSendInterval()){//发帖间隔小于发帖时间间隔
                return ResponseResult.buildResult(400,"您刚刚发过一篇文章咯，休息一下再来发帖吧！");
            }
        }
        //判断该成员等级
        if(circleMemberInfo.getRank()==1){//非正式圈员
            if(AssertUtil.isNotEmpty(articleInfoList) && articleInfoList.size()>=circleInfo.getSendArticleTotal()){
                return ResponseResult.buildResult(400,"您今天的发帖数已达上限，加入圈子发帖不受限制！");
            }
        }
        if(circleMemberInfo.getRank()<=3 && circleInfo.getIsProhibitionPublish()==2){//非圈主全体禁言
            return ResponseResult.buildResult(400,"该圈子当前已被禁言！");
        }
        //查询该圈子的一级分类及二级分类
        MenuLevelConfig menuLevel1 = menuLevelConfigService.findByMenuCode(circleInfo.getMainTypeCode());
        MenuLevelConfig menuLevel2 = menuLevelConfigService.findByMenuCode(circleInfo.getSubTypeCode());
        ArticleAuthVo result = new ArticleAuthVo();
        result.setCircleId(circleInfo.getId());
        result.setCircleRank(circleMemberInfo.getRank());
        result.setCircleTypeCode(menuLevel2.getMenuCode());
        result.setCircleTypeName(menuLevel2.getMenuName());
        result.setIsSetHot(menuLevel1.getIsSetHot());
        if("MQS00003".equals(menuLevel1.getMenuCode()) || "MQS00004".equals(menuLevel1.getMenuCode())){//足球和篮球
            result.setIsFree(2);
            //根据用户id查询文章收费定价
            ArticleChargePricingConfig articleChargePricingConfig = articleChargePricingConfigService.findByUserId(userId);
            result.setMinimumPrice(String.valueOf(articleChargePricingConfig.getMinimumPrice()));
            result.setMaximumPrice(String.valueOf(articleChargePricingConfig.getMaximumPrice()));
        }else{
            result.setIsFree(1);
        }
        return ResponseResult.buildResult(200,"可以发帖！", result);
    }


    /**
    * @Author: houjie
    * @Description: 是否可收费验证（用户是否认证）
    * @Date: 2019/4/10 10:57
    */
    @ApiOperation(value="是否可收费验证", notes="收费判断")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
    })
    @RequestMapping("/checkIsAuth")
    @ResponseBody
    public ResponseResult checkIsAuth(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String userId = reqParamMap.get("userId");
        if (StringUtils.isBlank(userId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "userId");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if(null != responseResult){
            return responseResult;
        }
        PortalUserInfo portalUserInfo = portalUserInfoService.findByUserId(userId);
        if(portalUserInfo.getUserType()==1){//未认证
            return ResponseResult.buildResult(400,"未认证");
        }else{
            return ResponseResult.buildResult(200,"已认证");
        }
    }



    /**
     * @Author: houjie
     * @Description: 发帖
     * @Date: 2019/4/8 14:47
     */
    @ApiOperation(value="发帖", notes="用户发帖")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "circleId", value = "圈子id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isHot", value = "是否进入热帖（1：否；2：是）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "publicType", value = "比赛公开类型（-1：永不；1：一天后；2：二天后；3：三天后；4：四天后；5：五天后；6：六天后；7：七天后）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isCharge", value = "是否收费（1：否；2：是）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "chargeAmount", value = "收费金额", required = false, dataType = "String"),
            @ApiImplicitParam(name = "articleTitle", value = "文章标题", required = false, dataType = "String"),
            @ApiImplicitParam(name = "freeContentSort", value = "免费内容排序规则", required = true, dataType = "String"),
            @ApiImplicitParam(name = "freeArticleContents", value = "免费文章内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "freeArticleImages", value = "免费文章图片", required = false, dataType = "String"),
            @ApiImplicitParam(name = "freeArticlsCompetitionIds", value = "免费文章赛事id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "paidContentSort", value = "付费内容排序规则", required = false, dataType = "String"),
            @ApiImplicitParam(name = "paidArticleContents", value = "付费文章内容", required = false, dataType = "String"),
            @ApiImplicitParam(name = "paidArticlsCompetitionIds", value = "付费文章赛事id", required = false, dataType = "String")
    })
    @RequestMapping("/postArticle" )
    @ResponseBody
    public ResponseResult postArticle(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String userId = reqParamMap.get("userId");
        if (StringUtils.isBlank(userId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "userId");
        }
        String circleId = reqParamMap.get("circleId");
        if (StringUtils.isBlank(circleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "circleId");
        }
        String isHot = reqParamMap.get("isHot");
        if (StringUtils.isBlank(isHot)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "isHot");
        }
        String publicType = reqParamMap.get("publicType");
        if (StringUtils.isBlank(publicType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "publicType");
        }
        String isCharge = reqParamMap.get("isCharge");
        if (StringUtils.isBlank(isCharge)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "isCharge");
        }
        String freeContentSort = reqParamMap.get("freeContentSort");
        if (StringUtils.isBlank(freeContentSort)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "freeContentSort");
        }
        String freeArticleContents = reqParamMap.get("freeArticleContents");
        if (StringUtils.isBlank(freeArticleContents)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "freeArticleContents");
        }/*else{
            reqParamMap.put("freeArticleContents", StringUtil.urlCodeToStr(reqParamMap.get("freeArticleContents")));
        }

        if(AssertUtil.isNotEmpty(reqParamMap.get("articleTitle"))){
            reqParamMap.put("articleTitle", StringUtil.urlCodeToStr(reqParamMap.get("articleTitle")));
        }
        if(AssertUtil.isNotEmpty(reqParamMap.get("freeArticleImages"))){
            reqParamMap.put("freeArticleImages", StringUtil.urlCodeToStr(reqParamMap.get("freeArticleImages")));
        }
        if(AssertUtil.isNotEmpty(reqParamMap.get("freeArticlsCompetitionIds"))){
            reqParamMap.put("freeArticlsCompetitionIds", StringUtil.urlCodeToStr(reqParamMap.get("freeArticlsCompetitionIds")));
        }
        if(AssertUtil.isNotEmpty(reqParamMap.get("paidArticleContents"))){
            reqParamMap.put("paidArticleContents", StringUtil.urlCodeToStr(reqParamMap.get("paidArticleContents")));
        }
        if(AssertUtil.isNotEmpty(reqParamMap.get("paidArticlsCompetitionIds"))){
            reqParamMap.put("paidArticlsCompetitionIds", StringUtil.urlCodeToStr(reqParamMap.get("paidArticlsCompetitionIds")));
        }*/

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if(null != responseResult){
            return responseResult;
        }
        //敏感词汇验证(要放入数据库)
        List<VocabularyFilterConfig> vocabularyFilterConfigList = articleInfoService.findVocabularyFilterConfigList();
        if(AssertUtil.isNotEmpty(vocabularyFilterConfigList) && vocabularyFilterConfigList.size()>0){
            responseResult = articleInfoService.vocabularyFilter(reqParamMap,vocabularyFilterConfigList);
            if(null != responseResult){
                return responseResult;
            }
        }
        return articleInfoService.insertArticleInfo(reqParamMap,request);
    }


}
